class Main extends egret.DisplayObjectContainer {
    private background: egret.Bitmap;
    private boss: egret.Bitmap;
    private speed: number;
    private direction: number;
    private yDirection: number;

    public constructor() {
        super();
        this.addEventListener(egret.Event.ADDED_TO_STAGE, this.onAddToStage, this);
    }

    private onAddToStage(event: egret.Event) {
        RES.addEventListener(RES.ResourceEvent.CONFIG_COMPLETE, this.onConfigComplete, this);
        RES.loadConfig("resource/default.res.json", "resource/");
    }

    private onConfigComplete(event: RES.ResourceEvent) {
        RES.removeEventListener(RES.ResourceEvent.CONFIG_COMPLETE, this.onConfigComplete, this);
        RES.addEventListener(RES.ResourceEvent.GROUP_COMPLETE, this.onResourceLoadComplete, this);
        RES.loadGroup("preload");
    }

    private onResourceLoadComplete(event: RES.ResourceEvent) {
        if (event.groupName == "preload") {
            RES.removeEventListener(RES.ResourceEvent.GROUP_COMPLETE, this.onResourceLoadComplete, this);
            this.createGameScene();
        }
    }

    private createGameScene(): void {
        this.background = new egret.Bitmap();
        this.background.texture = RES.getRes("fly_bg_jpg");
        this.addChild(this.background);

        this.boss = new egret.Bitmap();
        this.boss.texture = RES.getRes("boss_png");
        this.addChild(this.boss);
        this.boss.addEventListener(egret.Event.ENTER_FRAME, this.onEventFrame, this);

        this.speed = 1;
        this.direction = 1;
    }

    private onEventFrame(event: egret.Event) {
        let x = this.boss.x;
        let y = this.boss.y;
        if (y < (this.stage.stageHeight - this.boss.height) / 2-this.boss.height && y > 0) {
            this.boss.y += this.speed * this.yDirection;
        } else if (y <= 0) {
            this.boss.y += this.speed;
            this.yDirection = 1;
        } else {
            this.boss.y -= this.speed;
            this.yDirection = -1;
        }

        if (x < this.stage.stageWidth - this.boss.width && x > 0) {
            this.boss.x += this.speed * this.direction;
        } else if (x <= 0) {
            this.boss.x += this.speed;
            this.direction = 5;
        } else {
            this.boss.x -= this.speed;
            this.direction = -5;
        }
    }
}